package com.web;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import static com.web.JsonUtils.readValue;
import static org.apache.http.Consts.UTF_8;
import static org.apache.http.HttpStatus.SC_OK;

/**
 * 用于处理HTTP请求返回文件
 *
 * @author：zhang guoxiang
 * @date：2022/4/15
 */
public abstract class FileResponseUtils {

    @SneakyThrows
    public static InputStream handler(Response response) {
        HttpResponse httpResponse = response.returnResponse();
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        HttpEntity entity = httpResponse.getEntity();
        Content content = entity != null ?
                new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity)) :
                Content.NO_CONTENT;

        if (statusCode != SC_OK) {
            String responseBody = content.asString(UTF_8);
            throw new HttpResponseException(parseErrorMessage(responseBody));
        }

        return content.asStream();
    }

    @SuppressWarnings("unchecked")
    private static String parseErrorMessage(String responseBody) {
        Object object = StringUtils.isNotBlank(responseBody) ? readValue(responseBody, new TypeReference<Object>() {
        }) : null;
        if (object != null && !(object instanceof List)) {
            Map<String, Object> result = (Map<String, Object>) object;
            return (String) result.getOrDefault("error", "");
        }

        return "";
    }
}
